package com.tjshop.android.db;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.tjshop.android.model.userInfo;

public class userAccess {

	private static DBHelper dbHelper;

	public userAccess(Context context) {
		dbHelper = DBHelper.getInstance(context);
	}

	public userInfo getUserInfo() {
		Cursor cursor = dbHelper
				.query("select * from users where login_time in (select MAX(login_time) from users)",
						new String[] {});
		userInfo info = new userInfo();
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			info.setId(cursor.getString(0));
			info.setName(cursor.getString(1));
			info.setType(cursor.getString(2));
			info.setId_str(cursor.getString(3));
			info.setAdd_time(cursor.getString(4));
		} else {
			info = null;
		}
		cursor.close();
		return info;
	}

	public int getIsExist(String id) {
		Cursor cursor = dbHelper.query("select count(*) from users where id=?",
				new String[] { id });
		int iRet = 0;
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			iRet = cursor.getInt(0);
		}
		cursor.close();
		return iRet;
	}

	public void insertUser(userInfo info) {
		if (getIsExist(info.getId()) == 0) {
			ContentValues userInfo = new ContentValues();
			userInfo.put("id", info.getId());
			userInfo.put("name", info.getName());
			userInfo.put("type", info.getType());
			userInfo.put("id_str", info.getId_str());
			userInfo.put("add_time", info.getAdd_time());
			userInfo.put("add_time", info.getAdd_time());
			SimpleDateFormat sDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			String date = sDateFormat.format(new java.util.Date());
			userInfo.put("login_time", date);
			dbHelper.insert("users", userInfo);
		} else {
			updateLoginTime(info.getId());
		}
	}

	public void updateLoginTime(String id) {
		ContentValues values = new ContentValues();
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		String date = sDateFormat.format(new java.util.Date());
		values.put("login_time", date);
		dbHelper.update("users", values, "id=?", new String[] { id });
	}

	public void deleteUser(String username) {
		dbHelper.delete("users", "username=?", new String[] { username });
	}

}
